package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.util.Convert;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl extends ServiceImpl<BpmnInfoMapper, BpmnInfo> implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public boolean save(BpmnInfo BpmnInfo) {
        return bpmnInfoMapper.insert(BpmnInfo) > 0;
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo BpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(BpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        // 将字符串转为Long数组
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    @Transactional
    public void deploy(String bpmnPath, String bpmnType, String info) throws FileNotFoundException {

        // 获取部署对象
        Deployment deployment = repositoryService.createDeployment()
                .addInputStream(bpmnPath, new FileInputStream(new File(SystemConfig.getProfile(), bpmnPath)))
                .deploy();

        // 创建bpmn对象
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeploymentId(deployment.getId());
        bpmnInfo.setDeployTime(new Date());
        bpmnInfo.setInfo(info);

        // 获取流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployment.getId())
                .singleResult();
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());

        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    @Transactional
    public InputStream getResource(String deploymentId, String type) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        InputStream inputStream = null;
        // 获取xml文件
        if ("xml".equalsIgnoreCase(type)) {
            inputStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        } else if ("png".equalsIgnoreCase(type)){    // 获取png文件
            // 获取bpmn模型
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            // 创建默认流程图生成器对象
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            // 生成流程图
            inputStream = generator.generateDiagram(bpmnModel, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体", "宋体", "宋体");
        }
        return inputStream;
    }

    @Override
    @Transactional
    public void removeByBpmnInfoId(Long id) {
        // 先获取bpmn
        BpmnInfo bpmnInfo = this.get(id);
        // 后删除bpmn
        bpmnInfoMapper.deleteByPrimaryKey(id);

        // TODO
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(bpmnInfo.getActProcessKey())
                .singleResult();

        // 删除流程定义
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);
    }

    @Override
    public BpmnInfo queryByType(String bpmnType) {
        return bpmnInfoMapper.selectByBpmnType(bpmnType);
    }
}
